import { defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import AutoImport from 'unplugin-auto-import/vite'
import { createHtmlPlugin } from 'vite-plugin-html'
import Components from 'unplugin-vue-components/vite'
import postCssPxToRem from 'postcss-pxtorem'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import { VantResolver } from '@vant/auto-import-resolver'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default ({ mode }: UserConfig) => {
  // 获取.env文件里定义的环境变量
  const env = loadEnv(mode || 'development', process.cwd())
  const isBuild = mode === 'production'
  return defineConfig({
    base: env.VITE_BASE || '/',
    plugins: [
      vue(),
      VueSetupExtend(),
      Components({
        dts: 'src/types/components.d.ts',
        resolvers: [VantResolver()]
      }),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: env.VITE_APP_TITLE || 'vue3+ts'
          }
        },
        verbose: false
      }),
      viteCompression({
        // gzip压缩
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/ // .vue
        ],
        dirs: [
          'src/components/',
          'src/layout/',
          'src/assets',
          'src/enums/',
          'src/router',
          'src/service/api',
          'src/store',
          'src/utils',
          'src/views',
          'src/types'
        ],
        dts: 'src/types/auto-imports.d.ts',
        imports: [
          'vue',
          'vue-router',
          'pinia',
          '@vueuse/core',
          { 'lodash-es': [['*', 'Lodash']] },
          { axios: [['default', 'Axios']] }
        ],
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true
        }
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      port: 4321,
      host: '0.0.0.0',
      hmr: true,
      open: false
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: ({ file }) => {
              return file.indexOf('vant') !== -1 ? 37.5 : 75
            }, // 75表示750设计稿，37.5表示375设计稿
            unitPrecision: 5, // 单位转换后保留的精度
            selectorBlackList: ['ignore-'], // 需要忽略的CSS选择器，不会转为视口单位，使用原有的px等单位。
            exclude: /node_modules/i,
            propList: ['*']
          })
        ]
      }
    },
    build: {
      // chunkSizeWarningLimit: 900,
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash:8].js',
          entryFileNames: 'js/[name]-[hash:8].js',
          assetFileNames: '[ext]/[name]-[hash:8].[ext]',
          manualChunks(id) {
            // 静态资源分拆打包
            if (id.includes('node_modules')) {
              const chunkFileNames = id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
              // 这里需要去掉开头的. 例如.pnpm-56sdf.css,不去掉.目录删不干净
              return chunkFileNames.startsWith('.')
                ? chunkFileNames.slice(1).toString()
                : chunkFileNames.toString()
            }
          }
        }
      }
    },
    // 预加载构建配置（首屏性能)
    optimizeDeps: {
      esbuildOptions: {
        target: 'es2020'
      },
      // 提前预加载依赖，缩短首屏访问时间
      include: [
        'axios',
        'pinia',
        'vue',
        'vue-router',
        '@vueuse/core',
        'lodash-es'
      ]
    }
  })
}
